package uk.co.aetherworks.osc_messaging;

/*
 * Ped-ome
 *
 * MonToPed - Receives Messages from Monome Device
 *
 * Joe Handford aka Knecht 2011
 *
 */ 

// OSC Include Files
import com.illposed.osc.OSCPortOut;
import com.illposed.osc.OSCPortIn;
import com.illposed.osc.OSCListener;
import com.illposed.osc.OSCMessage;

// Java Net Include Files

import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

// aetherworks imports
import uk.co.aetherworks.debug.*;
 
public class MonToPed extends Debuggable implements MonCmdListener {

	OSCPortIn receiver;
	MonomeCmdInterpreter monomeListener;
	
	// pedListeningPort fixed - might be better to get next free
	public MonToPed(int pedListeningPort, OSCCmdHandler handler) {
		DEBUG("** Creating MonToPed bound to port: " + pedListeningPort);
		try
        {
            receiver = new OSCPortIn(pedListeningPort);
        }
        catch (Exception e) { System.out.println("Couldn't create pedome from monome receiver!"); }

	    monomeListener = new MonomeCmdInterpreter(this, handler);
		
		receiver.addListener("/sys/port", monomeListener);
		receiver.addListener("/sys/prefix", monomeListener);
		receiver.addListener("/sys/id", monomeListener);
		receiver.startListening();
	}
	
	public void attachForwarder(PedToApp aForwarder) {
	    monomeListener.attachForwarder(aForwarder);
	}
	
	public void detachForwarder() {
	    monomeListener.detachForwarder();
	}

	public void updateListeners(String prefix) {
		DEBUG("Updating MonToPed's listeners...");
		receiver.addListener(prefix + "/grid/key", monomeListener);
		receiver.addListener(prefix + "/tilt", monomeListener);
// DEBUG
		receiver.addListener("/grid/key", monomeListener);
		receiver.addListener("/tilt", monomeListener);
// DEBUG
	}
	
	public void setAppPrefix(String prefix) {
		monomeListener.setAppPrefix(prefix);
	}

	public void close() {
		receiver.stopListening();
		receiver.close();
	}
}
